﻿using System.Threading.Tasks;

namespace NetworkLibrary
{
    public class RpcCommand<TRequest> : BaseRpcCommand 
        where TRequest : IMessage
    {
        public RpcCommand(IProcedureCallService service) : base(service) { }
        public void Call(TRequest args)
        {
            AsyncCall(args).Wait();
        }
        public async Task AsyncCall(TRequest message)
        {
            var (code, msg) = await _service.Request(GetTypeId<TRequest>(), message);
            if (code != 0)
            {
                HandleError(code, msg);
            }
        }
    }

    public class RpcCommand<TRequest, TResponse> : BaseRpcCommand
        where TRequest : IMessage
        where TResponse : IMessage
    {
        public RpcCommand(IProcedureCallService service) : base(service) { }
        public TResponse Call(TRequest args)
        {
            var task = AsyncCall(args);
            task.Wait();
            return task.Result;
        }
        public async Task<TResponse> AsyncCall(TRequest message)
        {
            var (code, msg) = await _service.Request(GetTypeId<TRequest>(), message);
            if (code == 0 && msg is TResponse result)
            {
                return result;
            }
            HandleError(code, msg);
            return default;
        }

    }
}
